package com.jiang.专题.动态规划.Q368;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author Jiang
 * @version 1.0
 * @date 2025/02/22 13:39
 */
class Solution {
    public List<Integer> largestDivisibleSubset(int[] nums) {
        int n = nums.length;
        Arrays.sort(nums);
        int[] dp = new int[n];
        Arrays.fill(dp, 1);

        int maxValue = nums[0];
        int maxCnt = 1;

        for (int i = 1; i < n; i++) {
            for (int j = 0; j < i; j++) {
                if (nums[i] % nums[j] == 0) {
                    dp[i] = Math.max(dp[i], dp[j] + 1);
                }
            }

            if (dp[i] > maxCnt) {
                maxCnt = dp[i];
                maxValue = nums[i];
            }
        }

        List<Integer> res = new ArrayList<>();

        for (int i = n - 1; i >= 0 && maxCnt > 0; i--) {
            if (maxCnt == dp[i] && maxValue % nums[i] == 0) {
                maxCnt--;
                maxValue = nums[i];
                res.add(nums[i]);
            }
        }

        return res;
    }
}
